/**
 * Controller table.
 */
var controllerTable = {};
var prefix = "o:c:";
var s_key = "o:c:s";
var prefix_port = "o:c:p:";

function gettime() {
	"use strict";
	var d = new Date();
	return d.toUTCString();
}

function defaultCallback(err) {
	if (err) {
		console.error("controllerTable redis error:" + err);
	}
}

controllerTable.add = function(context, creg, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + creg.devId;
	
	var fields = [];
	fields.push(key);
	fields.push("devId");
	fields.push(creg.devId);
	fields.push("gwId");
	fields.push(creg.gwId);
	fields.push("description");
	fields.push(creg.description);
	fields.push("logintime");
	fields.push(gettime());
	fields.push("online");
	fields.push("true");

	context.beginMulti();
	redis.sadd(s_key, creg.devId, defaultCallback);
	redis.hmset(fields, callback);
	
	var ctrlId = creg.devId;
	var ports = creg.ports;
	var port_key = prefix_port + ctrlId;
	redis.del(port_key, callback);
	
	ports.forEach(function(port){
		var fi = port.index;
		redis.hset(port_key, fi, JSON.stringify(port), defaultCallback);
	});
	context.endMulti(defaultCallback);
};

controllerTable.loadPort = function(context, ctrlId, index, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var port_key = prefix_port + ctrlId;
	redis.hget(port_key, index, callback);
};

controllerTable.loadPorts = function(context, ctrlId, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var port_key = prefix_port + ctrlId;
	redis.hgetall(port_key, callback);
};

controllerTable.loadFields = function(context, id, fields, callback) {
	"use strict";
	var redis = context.redis;
	
	var key = prefix + id;
	redis.hmget(key, fields, callback);
};

controllerTable.setFields = function(context, id, fields, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + id;
	var fields2 = [key];
	fields2 = fields2.concat(fields);
	redis.hmset(fields2, callback);
};

controllerTable.del = function(context, id, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	var key = prefix + id;
	context.beginMulti();
	redis.srem(s_key, id, defaultCallback);
	redis.del(key, callback);
	var port_key = prefix_port + id;
	redis.del(port_key, callback);
	context.endMulti(defaultCallback);
};

controllerTable.scan = function(context, cursor, count, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	redis.sscan([s_key, cursor, "COUNT", count], callback);
};

controllerTable.count = function(context, callback) {
	"use strict";
	var redis = context.redis;
	if (!callback) {
		callback = defaultCallback;
	}
	
	redis.scard(s_key, callback);
};

module.exports = controllerTable;
